package org.stars.dao.loader;

import java.io.File;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.Format;

public class XmlBaseLoader<E, I> { 
	
	@SuppressWarnings("unchecked")
	E load(String name, InputStream inputStream, Class<I> clazz) throws Exception {
		I item = null;		

		Log log = LogFactory.getLog(getClass());
		try {			
			Serializer serializer = new Persister();
			item = serializer.read(clazz, inputStream);			
		} catch (Exception e) {
			log.error("Failed to load file " + name+" cause: "+e.getMessage());
			throw(e);
		}

		return (E) item;
	}
	
	@SuppressWarnings("unchecked")
	E load(String fileName, Class<I> clazz) throws Exception {
		I item = null;
		File fileConfig = new File(fileName);

		Log log = LogFactory.getLog(getClass());
		try {
			
			if (!fileConfig.exists()) {
				log.error("File not found " + fileConfig.getAbsolutePath());
			} else {
				
				Serializer serializer = new Persister();
				item = serializer.read(clazz, fileConfig);
				
				log.debug("Loaded file " + fileConfig.getAbsolutePath());
			}
		} catch (Exception e) {
			log.error("Failed to load file " + fileConfig.getAbsolutePath()+" cause: "+e.getMessage());
			throw(e);
		}

		return (E) item;
	}

	public boolean save(String fileName, E item) throws Exception {
		Log log = LogFactory.getLog(getClass());
		File fileConfig = new File(fileName);
		try {
			Format format = new Format("<?xml version=\"1.0\"?>");
			Persister serializer = new Persister(format);

			serializer.write(item, fileConfig);
			log.info("Load file " + fileConfig.getAbsolutePath());
			return true;

		} catch (Exception e) {
			log.error("Failed to save file " + fileConfig.getAbsolutePath()+" cause: "+e.getMessage());
			throw(e);
		}
	}
}
